package cn.iocoder.yudao.module.system.dal.mysql.appversion;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.appversion.AppVersionDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.system.controller.admin.appversion.vo.*;
import org.apache.ibatis.annotations.Select;

/**
 * App版本控制 Mapper
 *
 * @author 韩艳阳
 */
@Mapper
public interface AppVersionMapper extends BaseMapperX<AppVersionDO> {

    default PageResult<AppVersionDO> selectPage(AppVersionPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<AppVersionDO>()
                .eqIfPresent(AppVersionDO::getRemark, reqVO.getRemark())
                .eqIfPresent(AppVersionDO::getDeptId, reqVO.getDeptId())
                .betweenIfPresent(AppVersionDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(AppVersionDO::getPlatform, reqVO.getPlatform())
                .eqIfPresent(AppVersionDO::getUpdateLog, reqVO.getUpdateLog())
                .likeIfPresent(AppVersionDO::getVersionName, reqVO.getVersionName())
                .eqIfPresent(AppVersionDO::getVersionCode, reqVO.getVersionCode())
                .betweenIfPresent(AppVersionDO::getPublishTime, reqVO.getPublishTime())
                .eqIfPresent(AppVersionDO::getMinVersionCode, reqVO.getMinVersionCode())
                .eqIfPresent(AppVersionDO::getUpdateType, reqVO.getUpdateType())
                .eqIfPresent(AppVersionDO::getDownloadUrl, reqVO.getDownloadUrl())
                .orderByDesc(AppVersionDO::getId));
    }

    @Select("SELECT t1.* \n" +
            "FROM system_app_version t1 \n" +
            "INNER JOIN (\n" +
            "    SELECT platform, MAX(version_code) AS max_version_code \n" +
            "    FROM system_app_version \n" +
            "    WHERE deleted = 0  -- 子查询中排除已删除\n" +
            "    GROUP BY platform\n" +
            ") t2 \n" +
            "ON t1.platform = t2.platform AND t1.version_code = t2.max_version_code\n" +
            "WHERE t1.deleted = 0;  -- 主查询中排除已删除")
    List<AppVersionDO> selectLatestVersionsPerPlatform();

}
